package com.example.zsydb.service;

import com.example.zsydb.repository.ResultRepository;
import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;

import com.fasterxml.jackson.databind.node.ObjectNode;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonParseException;
// 新增必要导入
import com.fasterxml.jackson.core.JsonLocation;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.json.JsonReadFeature;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class PythonService {

    private static final Logger logger = LoggerFactory.getLogger(PythonService.class);

    public String executePythonScript(List<Map<String, Object>> data)
            throws IOException, InterruptedException {
        // 1. 数据转JSON文件（原有代码）
        ObjectMapper mapper = new ObjectMapper();
        File tempFile = File.createTempFile("spring-data-", ".json");
        mapper.writeValue(tempFile, data);

        // 2. 构建Python命令（原有代码）
//        String pythonScriptPath = "E:\\Download\\QQ\\oil2chang\\program\\二厂计产计液面诊断9.23.py";// 王德林电脑python路径

        String pythonScriptPath = "E:\\oil2chang\\program\\二厂计产计液面诊断9.23.py";// 二厂电脑python路径

        ProcessBuilder pb = new ProcessBuilder("python", pythonScriptPath, tempFile.getAbsolutePath());
        pb.redirectErrorStream(true);

        // 3. 执行并捕获输出
        Process process = pb.start();

        List<String> outputLines = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                outputLines.add(line);
            }
        }
        //打印outputLines
//        for (String line : outputLines) {
//            System.out.println("outputLines"+line);
//        }
        // 提取目标JSON（新增方法）
        String jsonResult = findTargetJson(outputLines, data);
//        System.out.println("jsonResult-----"+jsonResult);


        if (jsonResult == null) {
            //打印outputLines
//            for (String line : outputLines) {
//                System.out.println("outputLines"+line);
//            }
            throw new RuntimeException("python输出空数组或解析失败");
        }

        return jsonResult;
    }

    public String findTargetJson(List<String> outputLines, List<Map<String, Object>> data) {
        // 创建配置了特殊解析功能的ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        // 关键修改点：允许解析NaN/Infinity等特殊值
        mapper.enable(JsonReadFeature.ALLOW_NON_NUMERIC_NUMBERS.mappedFeature());

        // 记录输出行数和合并后的输出概况
//        logger.info("开始解析Python输出，输出行数：{}", outputLines.size());
        String fullOutput = String.join("", outputLines).trim();

        // 记录合并后输出的摘要信息
        logger.debug("合并后的完整输出长度：{}", fullOutput.length());
        if (!fullOutput.isEmpty()) {
            int previewLength = Math.min(200, fullOutput.length());
            logger.debug("合并后的输出前{}字符：{}", previewLength,
                    fullOutput.substring(0, previewLength));
            logger.debug("合并后的输出后{}字符：{}", previewLength,
                    fullOutput.substring(Math.max(0, fullOutput.length() - previewLength)));
        } else {
            logger.warn("合并后的输出为空字符串");
        }

        // 查找最后一个闭合的']'的位置
        int lastCloseIndex = fullOutput.lastIndexOf(']');
        logger.debug("最后一个']'的位置：{}", lastCloseIndex);
        if (lastCloseIndex == -1) {
            logger.error("未找到闭合的']'，无法提取JSON数组，完整输出可能包含非JSON内容");
            return null;
        }

        // 查找匹配的'['
        int lastOpenIndex = fullOutput.lastIndexOf('[', lastCloseIndex);
        logger.debug("在位置{}之前最近的'['位置：{}", lastCloseIndex, lastOpenIndex);
        if (lastOpenIndex == -1) {
            logger.error("未找到匹配的'['，可能JSON结构不完整或被非JSON内容污染");
            return null;
        }

        // 提取并验证JSON段
        String potentialJson = fullOutput.substring(lastOpenIndex, lastCloseIndex + 1);
        logger.info("提取潜在JSON段，长度：{}", potentialJson.length());

        // 新增结构验证日志
        if (!potentialJson.startsWith("[") || !potentialJson.endsWith("]")) {
            logger.error("截取的JSON段结构不合法，起始字符：{}，结束字符：{}",
                    potentialJson.length() > 0 ? potentialJson.charAt(0) : "空",
                    potentialJson.length() > 0 ? potentialJson.charAt(potentialJson.length()-1) : "空");
            return null;
        }

        try {
            // 新增解析进度跟踪
            logger.debug("开始解析JSON数据...");
            List<Map<String, Object>> pythonResults = mapper.readValue(
                    potentialJson,
                    new TypeReference<List<Map<String, Object>>>() {}

            );
            logger.info("成功解析出{}条Python结果", pythonResults.size());
//            System.out.println("pythonResult"+pythonResults);

            if (pythonResults == null || pythonResults.isEmpty()) {
                logger.warn("解析结果为空列表");
                return null;
            }


            // 新增第一条结果样本日志
            if (logger.isDebugEnabled() && !pythonResults.isEmpty()) {
                logger.debug("第一条结果样本：{}", mapper.writeValueAsString(pythonResults.get(0)));
            }

            return mergeDataWithPythonResults(pythonResults, data, mapper);
        } catch (IOException e) {
            // 增强错误定位信息
            if (e instanceof JsonParseException) {
                JsonLocation location = ((JsonParseException) e).getLocation();
                logger.error("解析失败位置：[行:{} 列:{}] 偏移量:{}",
                        location.getLineNr(),
                        location.getColumnNr(),
                        location.getCharOffset());
            }

            // 记录错误片段上下文
            int errorPosition = getErrorPosition(e);
            if (errorPosition > 0) {
                int start = Math.max(0, errorPosition - 50);
                int end = Math.min(potentialJson.length(), errorPosition + 50);
                logger.error("错误上下文：{}...{}",
                        potentialJson.substring(start, errorPosition),
                        potentialJson.substring(errorPosition, end));
            }

            logger.error("解析潜在JSON时发生异常：{}", e.getMessage());
            logger.error("解析失败的JSON片段（前500字符）：{}",
                    potentialJson.substring(0, Math.min(500, potentialJson.length())));
            logger.error("完整解析异常堆栈：", e);
            return null;
        }
    }

    // 辅助方法：从异常中获取错误位置
    private int getErrorPosition(IOException e) {
        if (e instanceof JsonParseException) {
            return (int) ((JsonParseException) e).getLocation().getCharOffset();
        }
        return -1;
    }

    private String mergeDataWithPythonResults(List<Map<String, Object>> pythonResults, List<Map<String, Object>> data, ObjectMapper mapper) throws JsonProcessingException {
        List<Map<String, Object>> mergedDataList = new ArrayList<>();

        // 需要从原始数据中提取的字段列表
        String[] dataFields = {
                "DYNA_CREATE_TIME", "ID", "CHECK_DATE", "STROKE", "FREQUENCY",
                "SUSP_MAX_LOAD", "SUSP_MIN_LOAD", "UPGOING_MAX_CURRENT", "DOWNGOING_MAX_CURRENT",
                "DISPLACEMENT","DISP_LOAD","DISP_CURRENT","ACTIVE_POWER",
                "GGGF", "GGCD", "CYGGF1", "CYGCD1", "CYGGF2", "CYGCD2", "YY", "TY", "HS", "BJ", "BS"
        };

        for (Map<String, Object> pythonEntry : pythonResults) {
//            String jh = (String) pythonEntry.get("JH");
            // 修复后的代码（推荐简单方案）
            String JH = String.valueOf(pythonEntry.get("JH"));

            // 新增检查：如果JH是无效值（如"0"），记录并跳过
            if ("0".equals(JH)) {
                logger.error("检测到无效的JH值: 0，跳过该条目。完整条目内容：{}", pythonEntry);
                continue;
            }



            // 在原始数据中查找匹配的JH条目
            Map<String, Object> matchedDataEntry = findDataEntryByJH(data, JH);
            if (matchedDataEntry == null) {
                // 输出当前所有JH值以便调试
                List<String> existingJHs = data.stream()
                        .map(e -> String.valueOf(e.get("JH")))
                        .collect(Collectors.toList());
                logger.error("在原始数据中未找到JH: {}，现有JH列表：{}", JH, existingJHs);
                throw new RuntimeException("在原始数据中未找到JH: " + JH);
            }

            // 合并Python结果和原始数据
            Map<String, Object> mergedEntry = new LinkedHashMap<>();
            // 添加Python结果中的字段
            mergedEntry.put("JH", JH);
            mergedEntry.put("GTZD", pythonEntry.get("GTZD"));
            mergedEntry.put("DYM", pythonEntry.get("DYM"));
            mergedEntry.put("CL", pythonEntry.get("CL"));

            // 添加原始数据中的字段
            for (String field : dataFields) {
                Object value = matchedDataEntry.get(field);
                // 处理可能的数值类型（例如将Integer转换为Double）
                if (value instanceof Number) {
                    value = ((Number) value).doubleValue();
                }
                mergedEntry.put(field, value);
            }

            mergedDataList.add(mergedEntry);
        }

        // 包装成最终的JSON结构
        Map<String, Object> finalResult = new HashMap<>();
        finalResult.put("data", mergedDataList);

        return mapper.writeValueAsString(finalResult);
    }

    private Map<String, Object> findDataEntryByJH(List<Map<String, Object>> data, String JH) {
        for (Map<String, Object> entry : data) {
            Object entryJH = entry.get("JH");
            if (entryJH != null && String.valueOf(entryJH).equals(JH)) {
                return entry;
            }
        }
        return null;
    }

//    private String findTargetJson(List<String> lines, List<Map<String, Object>> originalData) {
//        ObjectMapper mapper = new ObjectMapper();
//
//        // 将 originalData 转为 Map，避免反复遍历
//        Map<String, Map<String, Object>> jhMap = new HashMap<>();
//        for (Map<String, Object> map : originalData) {
//            Object jh = map.get("JH");
//            if (jh != null) {
//                jhMap.put(jh.toString(), map);
//            }
//        }
//
//        for (String line : lines) {
//            line = line.trim();
//            if (line.isEmpty() || !line.startsWith("[")) {
//                continue; // 快速排除非数组 JSON
//            }
//
//            try {
//                JsonNode node = mapper.readTree(line);
//
//                if (!node.isArray() || node.size() == 0) {
//                    continue;
//                }
//
//                boolean allValid = true;
//
//                for (JsonNode item : node) {
//                    if (!item.has("JH") || !item.has("GTZD") || !item.has("DYM") || !item.has("CL")) {
//                        allValid = false;
//                        break;
//                    }
//
//                    String jh = item.get("JH").asText();
//                    Map<String, Object> original = jhMap.get(jh);
//                    if (original == null) {
//                        continue;
//                    }
//
//                    ObjectNode itemNode = (ObjectNode) item;
//
//                    // 添加字符串字段
//                    String[] stringFields = {"DYNA_CREATE_TIME", "ID", "CHECK_DATE"};
//                    for (String field : stringFields) {
//                        if (original.containsKey(field)) {
//                            String value = String.valueOf(original.get(field));
//                            // 特殊处理CHECK_DATE字段，移除末尾的.0
//                            if ("CHECK_DATE".equals(field)) {
//                                value = value.replaceAll("\\.\\d+$", ""); // 使用正则移除毫秒部分
//                            }
//                            itemNode.put(field, value);
//                        }
//                    }
//
//                    // 添加数值字段
//                    String[] numericFields = {
//                            "STROKE", "FREQUENCY", "SUSP_MAX_LOAD", "SUSP_MIN_LOAD",
//                            "UPGOING_MAX_CURRENT", "DOWNGOING_MAX_CURRENT", "GGGF", "GGCD",
//                            "CYGGF1", "CYGCD1", "CYGGF2", "CYGCD2", "YY", "TY", "HS", "BJ", "BS"
//                    };
//                    for (String field : numericFields) {
//                        Object valueObj = original.get(field);
//                        if (valueObj == null) {
//                            itemNode.putNull(field);
//                            continue;
//                        }
//
//                        if (valueObj instanceof Number) {
//                            itemNode.put(field, ((Number) valueObj).doubleValue());
//                        } else {
//                            try {
//                                double parsedValue = Double.parseDouble(valueObj.toString());
//                                itemNode.put(field, parsedValue);
//                            } catch (NumberFormatException e) {
//                                itemNode.putNull(field);
//                                System.err.println("Field " + field + " is not a valid number: " + valueObj);
//                            }
//                        }
//                    }
//                }
//
//                if (!allValid) {
//                    continue;
//                }
//
//                ObjectNode wrapper = mapper.createObjectNode();
//                wrapper.set("data", node);
//                return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(wrapper);
//
//            } catch (Exception e) {
//                // 忽略无效行
//            }
//        }
//        return null;
//    }

}